package customizeservicelogic

import (
	"ToolLibray/pinyin"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"os"
	"property_service/dao/model"
	"property_service/internal/svc"
	"property_service/property_service"
	"property_service/utils/result"
)

type (
	InitializeTheDataLogic struct {
		ctx    context.Context
		svcCtx *svc.ServiceContext
		logx.Logger
	}
	AssetTypeList struct {
		AssetType []*model.AssetType `json:"asset_type"`
	}
)

func NewInitializeTheDataLogic(ctx context.Context, svcCtx *svc.ServiceContext) *InitializeTheDataLogic {
	return &InitializeTheDataLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// InitializeTheData 方法用于初始化指定表的数据
// 参数:
//   - l: InitializeTheDataLogic 结构体指针，包含初始化数据的逻辑
//   - in: property_service.Initialize 结构体指针，包含初始化所需的参数
//
// 返回值:
//   - *property_service.Response: 初始化操作后的响应结果
//   - error: 操作过程中可能出现的错误
func (l *InitializeTheDataLogic) InitializeTheData(in *property_service.Initialize) (*property_service.Response, error) {
	var err error
	//获取初始化json
	openFile, err := os.Open("etc/Initialize/Initialize.json")
	if err != nil {
		return result.Err(errors.New("生成文件不存在")).Ed()
	}
	defer openFile.Close()
	//通过判断in的tebalname
	switch in.TableName {
	case "asset_type":
		var res AssetTypeList
		if err := json.NewDecoder(openFile).Decode(&res); err != nil {
			// 解析文件失败，返回错误信息
			return result.Err(fmt.Errorf("出现问题, %s", err)).Ed()
		}
		//删除已有的数据
		if _, err = l.DelTableData("", "", in.TableName); err != nil {
			return result.Err(fmt.Errorf("删除数据失败, %s", err)).Ed()
		}
		//遍历赋值
		for _, i := range res.AssetType {
			i.PinyinCode = pinyin.ToPinyinInitials(i.Name)
			i.CreatedAtuser = in.UserIDS
			i.UpdatedAtuser = in.UserIDS
			i.TenantID = in.TenantID
		}
		//遍历数据，重置数据
		if err = l.svcCtx.Gorm.Create(res.AssetType).Error; err != nil {
			return result.Err(fmt.Errorf("添加数据失败, %s", err)).Ed()
		}
		//如果涉及到父级编码，则需要查询并修改赋值
		for _, i := range res.AssetType {
			if i.ParentCode != "" {
				_, err := l.UpParentIdByParentCode("code", "parent_id", in.TableName, in.TenantID, i.Code, i.ParentCode)
				if err != nil {
					return result.Err(fmt.Errorf("修改父级报错, %s", err)).Ed()
				}
			}
		}
		//返回成功信息
		return &property_service.Response{
			Code:    200,
			Message: fmt.Sprintf("初始化数据成功,表名:%s,条数:%d", in.TableName, len(res.AssetType)),
			Data:    nil,
		}, nil
	}

	return &property_service.Response{}, nil
}

// DelTableData 删除表数据
func (l *InitializeTheDataLogic) DelTableData(TenantID string, StockID string, TableName string) (*property_service.Response, error) {
	//获取表数据
	sql := "Delete from " + TableName
	//如果需要通过库ID查询
	if StockID != "" {
		sql += " where StockID = " + StockID
	}
	//如果需要通过租户ID查询
	if TenantID != "" {
		sql += " where TenantID = " + TenantID
	}
	//执行删除操作
	if err := l.svcCtx.Gorm.Exec(sql).Error; err != nil {
		//如果删除失败，返回错误信息
		return result.Err(fmt.Errorf("删除数据失败, %s", err)).Ed()
	}
	//删除成功，返回空响应
	return &property_service.Response{}, nil
}

// UpParentIdByParentCode 查询父级编码，并修改指定数据的父级id
func (l *InitializeTheDataLogic) UpParentIdByParentCode(CodeZd string, ParentIdZd string, TableName string, TenantID int64, Code string, ParentCode string) (*property_service.Response, error) {
	if ParentCode == "" || TableName == "" || ParentIdZd == "" || CodeZd == "" || Code == "" {
		return result.Err(errors.New("数据不能为空")).Ed()
	}
	parentId := ""
	//获取父级id
	if err := l.svcCtx.Gorm.Raw(fmt.Sprintf("SELECT id FROM %s WHERE %s = ? AND tenant_id = ?", TableName, CodeZd), ParentCode, TenantID).Scan(&parentId).Error; err != nil {
		return result.Err(fmt.Errorf("修改父级报错, %s", err)).Ed()
	}
	//如果父级id为空，则返回错误信息
	if parentId == "" {
		return result.Err(errors.New("父级id为空")).Ed()
	}
	sql2 := fmt.Sprintf("UPDATE %s SET %s = ? WHERE %s = ? AND tenant_id = ? ", TableName, ParentIdZd, CodeZd)
	fmt.Println(sql2)
	//修改父级id通过Code
	if err := l.svcCtx.Gorm.Raw(sql2, parentId, Code, TenantID).Scan(nil).Error; err != nil {
		return result.Err(fmt.Errorf("修改父级报错, %s", err)).Ed()
	}
	//修改成功，返回空响应
	return &property_service.Response{}, nil
}
